import axios, { AxiosResponse } from 'axios';
import crypto from 'crypto';

/**
 * 微信登录响应数据接口
 */
interface WechatLoginResponse {
  openid?: string;
  session_key?: string;
  unionid?: string;
  errcode?: number;
  errmsg?: string;
}

/**
 * 获取OpenID返回结果接口
 */
interface OpenidResult {
  success: boolean;
  data?: {
    openid: string;
    session_key: string;
    unionid?: string;
  };
  error?: string;
}

/**
 * 微信认证服务类
 */
export class WechatAuthService {
  private appId: string;
  private appSecret: string;

  constructor() {
    this.appId = process.env.WECHAT_APPID || '';
    this.appSecret = process.env.WECHAT_APP_SECRET || '';

    if (!this.appId || !this.appSecret) {
      console.warn('警告: 微信 AppID 或 AppSecret 未配置');
    }
  }

  /**
   * 通过code获取openid和session_key
   * @param code - 微信登录凭证
   * @returns 包含openid和session_key的对象
   */
  async getOpenidByCode(code: string): Promise<OpenidResult> {
    try {
      const url = 'https://api.weixin.qq.com/sns/jscode2session';
      const params = {
        appid: this.appId,
        secret: this.appSecret,
        js_code: code,
        grant_type: 'authorization_code'
      };

      const response: AxiosResponse<WechatLoginResponse> = await axios.get(url, { params });
      
      if (response.data.errcode) {
        throw new Error(`微信API错误: ${response.data.errmsg}`);
      }

      return {
        success: true,
        data: {
          openid: response.data.openid!,
          session_key: response.data.session_key!,
          unionid: response.data.unionid
        }
      };

    } catch (error: any) {
      console.error('获取openid失败:', error);
      return {
        success: false,
        error: error.message || '获取openid失败'
      };
    }
  }

  /**
   * 解密微信用户信息
   * @param encryptedData - 加密数据
   * @param iv - 初始向量
   * @param sessionKey - 会话密钥
   * @returns 解密后的用户信息
   */
  decryptUserInfo(encryptedData: string, iv: string, sessionKey: string): any {
    try {
      const sessionKeyBuffer = Buffer.from(sessionKey, 'base64');
      const encryptedDataBuffer = Buffer.from(encryptedData, 'base64');
      const ivBuffer = Buffer.from(iv, 'base64');
      
      const decipher = crypto.createDecipheriv('aes-128-cbc', sessionKeyBuffer, ivBuffer);
      decipher.setAutoPadding(true);
      
      let decrypted = decipher.update(encryptedDataBuffer, undefined, 'utf8');
      decrypted += decipher.final('utf8');
      
      return JSON.parse(decrypted);
    } catch (error) {
      console.error('解密用户信息失败:', error);
      throw new Error('解密失败');
    }
  }
}

// 创建单例实例并导出
const wechatAuthService = new WechatAuthService();
export default wechatAuthService;